﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psm.Util;

namespace Psm.PubSub.Serialization.Prefixed
{
    public class ByteBufferMessageDeserializer
    {
        private int _currentIndex;
        private ByteBuffer _buffer = null;

        public ByteBufferMessageDeserializer(ByteBuffer buffer, int padding = 1)
        {
            _buffer = buffer;
            _currentIndex = buffer.StartIndex + padding;
        }

        public bool HasMore()
        {
            return _currentIndex <= _buffer.EndIndex;
        }

        public string GetStringField()
        {
            ByteBuffer buffer = GetField();
            return ASCIIEncoding.ASCII.GetString(buffer.GetBuffer(), buffer.StartIndex, buffer.Length);
        }

        public ByteBuffer GetField()
        {
            int length = GetIntValue();
            ByteBuffer buffer = new ByteBuffer(_buffer.GetBuffer(), _currentIndex, _currentIndex + length, _currentIndex + length);
            _currentIndex += length;
            return buffer;
        }

        public void GetTuple(out int item1, out ByteBuffer item2)
        {
            item1 = GetIntValue();
            item2 = GetField();
        }

        public void GetTuple(out ByteBuffer item1, out ByteBuffer item2, out ByteBuffer item3)
        {
            item1 = GetField();
            item2 = GetField();
            item3 = GetField();
        }

        private int GetIntValue()
        {
            int value = BitConverter.ToInt32(_buffer.GetBuffer(), _currentIndex);
            _currentIndex += 4;
            return value;
        }
    }
}
